<template>
    <div class="h-full w-full">
      <admin-card-box>
        <template #header>
          <div class="flex justify-between">
            <h4>用户列表</h4>
            <div>
              <add-user @refresh="refresh"/>
            </div>
          </div>
        </template>
        <template #default>
          <el-table :data="list" v-loading="loading">
            <el-table-column
                v-for="(item,i) in columns" :key="i" :label="item.label" :prop="item.prop"></el-table-column>
            <el-table-column label="Create Time" prop="create_time">
              <template #default="{row}">
                <span>{{formatDate(row.create_time)}}</span>
              </template>
            </el-table-column>
            <el-table-column label="Operation">
              <template #default="{row}" >
                <el-popconfirm title="确定删除吗?" @confirm="handleDel(row.id)">
                  <template #reference>
                    <el-button round size="small" type="danger"><el-icon><delete/></el-icon></el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <div class="w-full my-2">
            <el-pagination
            :total="total" background :page-size="formParam.size" :current-page="formParam.page"
            @current-change="handlePageChanged"
            >
            </el-pagination>
          </div>
        </template>
      </admin-card-box>
    </div>
</template>

<script lang="ts" setup="setup">
import {reactive, toRef} from "vue";
import AdminCardBox from '@/components/common/AdminCardBox.vue';
import useUser from "@/hooks/useUser";
import {formatDate} from "@/helpers/utils";
import AddUser from "@/pages/admin/user/AddUser.vue";
import {Delete} from "@element-plus/icons-vue";
import {CODE_OK} from "@/api/consts";
import {ElMessage} from "element-plus";

const formParam =reactive({page:1,size:10});
const {userList,userDel} = useUser();
const {list ,total,loading,refresh} = userList(toRef(formParam,'page'),toRef(formParam,'size'),true);
const columns = [{
  label:'ID',
  prop:'id'
},{
  label:'Name',
  prop:'username'
},{
  label:'Email',
  prop:'email'
}, {
  label:'Role',
    prop:'role'
  }
];

const handlePageChanged=(p:number)=>{
  formParam.page=p;
};
const handleDel=(id:number)=>{
  userDel(id).then((res)=>{
    if(res.code===CODE_OK){
      ElMessage.success(res.msg);
      list.value = list.value.filter((it)=>{return it.id!=id;});
      return ;
    }
    ElMessage.error(res.msg);
  });
};
</script>

<style scoped lang="scss">

</style>